package com.m1book.site;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.m1book.domain.M1BookService;
import com.m1book.domain.book.ABook;
import com.m1book.domain.book.ABookState;
import com.m1book.domain.book.Book;
import com.m1book.domain.user.Miser;

@Controller
@SessionAttributes({"currentUser", "book", "bookInfo"})
@RequestMapping("/dona")
public class DonaController {
	private static final Logger logger = LoggerFactory.getLogger(DonaController.class);
	
	@Autowired
	private M1BookService m1BookService;
	
	@RequestMapping(value = "/todona", method = RequestMethod.GET)
	public String toDona(@ModelAttribute("currentUser") Miser miser, Model model) {
		model.addAttribute("currentUser", miser);
		return "dona/todona";
	}
	
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String dona(@ModelAttribute("currentUser") Miser miser, @ModelAttribute("book") Book book, Model model) {
		logger.info("miser " + miser.getId() + ", dona book id: " + book.getId() + ", book title: " + book.getTitle());
		String result = "dona/donaok";
		
		Date now = new Date();
		
		ABook abook = new ABook();
		abook.setBook(book);
		abook.setDonated(true);
		abook.setDonatorId(miser.getId());
		abook.setHolderId(miser.getId());
		abook.setRegisterTime(now);
		abook.setState(ABookState.REGISTERD);
		
		m1BookService.registerABook(miser, abook);
		
		model.addAttribute("abook", abook);
		
		return result;
	}

}
